// testlogserver project main.go
package main

import (
	"fmt"
	"io"
	"net"
	"strings"
	"time"
)

func main() {

	addr, err := net.ResolveTCPAddr("tcp", ":7020")
	if err != nil {
		fmt.Println(err)
		return
	}

	listener, err := net.ListenTCP("tcp", addr)
	if err != nil {
		fmt.Println(err)
		return
	}

	for {
		tcp, err := listener.AcceptTCP()
		if err != nil {
			fmt.Println(err)
			time.Sleep(time.Second)
			continue
		}

		go doConnWork(tcp)

	}

}

func doConnWork(conn *net.TCPConn) {
	fmt.Println("a client connected ip: %s", conn.RemoteAddr().String())
	defer func() {
		fmt.Println("a client disconnected ip: %s", conn.RemoteAddr().String())
	}()
	var msg string
	var err error

	for err != io.EOF {
		msg, err = readMsg(conn)
		if err != nil {

			fmt.Println(err)
			time.Sleep(time.Second)
			continue
		}
		fmt.Println(msg)
	}
}

func readMsg(conn *net.TCPConn) (msg string, err error) {
	data := make([]byte, 2048)
	n, err := conn.Read(data)
	if err != nil {
		return "", err
	}
	msg = string(data[:n])
	ss := strings.Split(msg, " ")
	for i, v := range ss {
		fmt.Println(i, v)
	}
	return
}
